package cookie.library.random;

import com.rsbuddy.script.ActiveScript;
import com.rsbuddy.script.methods.Environment;
import com.rsbuddy.script.methods.Game;
import com.rsbuddy.script.task.Task;
import org.rsbuddy.widgets.Bank;

import java.util.logging.Logger;

/**
 * @autor Sir Cookie
 */
public abstract class Random {
    private boolean enabled = true;
    private long timeout = com.rsbuddy.script.util.Random.nextInt(240, 300);

    private ActiveScript script;
    public final Logger log = Logger.getLogger("Random");

    public abstract boolean activate();

    public abstract int loop();

    public long getTimeout(final boolean minutes) {
        return minutes ? timeout : timeout * 1000;
    }

    public void setEnabled(final boolean b) {
        this.enabled = b;
    }

    public boolean stop(final boolean logout) {
        if (logout) {
            if (Bank.isOpen()) {
                Bank.close();
            }
            if (Game.isLoggedIn()) {
                Environment.disableRandoms();
                Game.logout(false);
            }
        }
        return script.stop();
    }

    public void run(final ActiveScript script) {
        try {
            this.script = script;
            String author = getClass().getAnnotation(Manifest.class).author();
            String name = getClass().getAnnotation(Manifest.class).name() + " v" + getClass().getAnnotation(Manifest.class).version();
            timeout = getTimeout(false) + System.currentTimeMillis();
            script.getThread().interrupt();
            log.info("Random event starting: " + name + ", by " + author);
            while (enabled) {
                try {
                    final int loop = loop();
                    if (loop == -1) {
                        setEnabled(false);
                        break;
                    } else if (System.currentTimeMillis() >= getTimeout(false)) {
                        log.severe("Time limit reached for " + name + ".");
                        stop(true);
                        setEnabled(false);
                        break;
                    } else {
                        Task.sleep(loop);
                    }
                } catch (Exception ex) {
                    log.severe("Exception thrown: " + ex);
                }
            }
            log.info("Random event finished: " + name);
            script.start();
            Task.sleep(1000);
        } catch (Exception ignored) {
        }
    }
}